import * as React from "react";
import { Button, Modal, Table } from "antd";
import * as echarts from "echarts";
import moment from "moment";
import { getDeviceListData } from "../../../ServeApi";
import { AjaxData } from "../../../../../../data/interface/publicInterface";
import DayOrHourTimePicker from "../DayOrHourTimePicker";
import ReactEcharts from "echarts-for-react";

export interface CalcModalProps {
  visible: boolean;
  attr: any;
  onOk: (data: any) => any;
  onCancel: (data: any) => any;
}

export interface CalcModalState {
  isModalVisible: boolean;
  defaultStart: number;
  defaultEnd: number;
}

class CalcModal extends React.Component<CalcModalProps, CalcModalState> {
  state = {
    isModalVisible: false,
    defaultStart: 0,
    defaultEnd: 0,
  };
  option = {};
  deviceId: string = "";
  timeType: number = 2;
  energyType: number = 1;
  columns: any[] = [];
  dataSouce: any[] = [];
  render() {
    let { isModalVisible } = this.state;
    return (
      <>
        <Modal
          title="用量图表 "
          visible={isModalVisible}
          onOk={() => {
            this.handleOk();
          }}
          onCancel={() => {
            this.handleCancel();
          }}
          width={800}
          style={{ top: 20 }}
        >
          <div>
            <DayOrHourTimePicker
              value={[
                moment(this.state.defaultStart),
                moment(this.state.defaultEnd),
              ]}
              onChange={(timeType: number, dateString: any[]) => {
                // this.getPream(timeType, dateString);
                this.timeType = timeType;
                this.setState({
                  defaultStart: dateString[0].valueOf(),
                  defaultEnd: dateString[1].valueOf(),
                });
                this.forceUpdate();
              }}
              mod="moment"
            />
            <Button
              type="primary"
              onClick={() => {
                this.getPream(this.timeType, [
                  moment(this.state.defaultStart),
                  moment(this.state.defaultEnd),
                ]);
              }}
            >
              搜索
            </Button>
          </div>
          <div>
            <ReactEcharts
              option={this.option}
              notMerge={true}
              lazyUpdate={true}
              style={{ height: 430 }}
            ></ReactEcharts>
          </div>
          <Table
            columns={this.columns}
            dataSource={this.dataSouce}
            style={{ paddingTop: 16 }}
          ></Table>
        </Modal>
      </>
    );
  }
  /**钩子函数 */
  shouldComponentUpdate(newProps: CalcModalProps, newState: CalcModalState) {
    if (newProps.visible !== this.props.visible) {
      console.log("钩子函数");
      this.setState({
        isModalVisible: newProps.visible,

        defaultStart: newProps.attr.start,
        defaultEnd: newProps.attr.end,
      });
      this.deviceId = newProps.attr.deviceId;
      this.timeType = newProps.attr.timeType;
      this.energyType = newProps.attr.energyType;
      this.getDataSouce(newProps.attr);
    }
    return true;
  }
  /**主动操作 */
  handleOk() {}
  handleCancel() {
    this.props.onCancel(false);
  }
  getPream(timeType: number, dateString: any[]) {
    let { deviceId, energyType } = this;
    let pream = {
      deviceId,
      start: dateString[0].valueOf(),
      end: dateString[1].valueOf(),
      timeType,
      energyType,
    };
    this.getDataSouce(pream);
  }
  getWaterData(timeType: number, data: any) {
    let time: string[] = [];
    let value: number[] = [];

    let columns: any[] = [];
    let dataSouce: any[] = [{}];
    data.map((item: any, index: number) => {
      let tStr =
        timeType === 1
          ? moment(item.dataTime).format("YYYY/MM/DD HH")
          : moment(item.dataTime).format("YYYY/MM/DD");
      columns.push({
        title: tStr,
        dataIndex: "columns" + index,
        key: "columns" + index,
      });
      //
      dataSouce[0]["columns" + index] = item.val;
      time.push(tStr);
      value.push(item.val);
      return item;
    });
    this.columns = columns;
    this.dataSouce = dataSouce;
    this.forceUpdate();
    return { time, value };
  }
  getEleData(timeType: number, data: any) {
    let time: string[] = [];
    let value: number[] = [];

    let columns: any[] = [];
    let dataSouce: any[] = [{}];
    data.map((item: any, index: number) => {
      let tStr =
        timeType === 1
          ? moment(item.dataTime).format("YYYY/MM/DD HH")
          : moment(item.dataTime).format("YYYY/MM/DD");
      columns.push({
        title: tStr,
        dataIndex: "columns" + index,
        key: "columns" + index,
      });
      //
      dataSouce[0]["columns" + index] = item.zyTVal;
      time.push(tStr);
      value.push(item.zyTVal);
      return item;
    });
    this.columns = columns;
    this.dataSouce = dataSouce;
    this.forceUpdate();
    return { time, value };
  }
  setOpction(data: { time: string[]; value: number[] }) {
    return {
      title: {
        text: "用量图表",
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
          label: {
            backgroundColor: "#62DAAA",
          },
        },
      },
      color: ["#62DAAA"],
      xAxis: [
        {
          type: "category",
          boundaryGap: false,
          data: data.time,
        },
      ],
      yAxis: [
        {
          type: "value",
        },
      ],
      series: [
        {
          type: "line",
          areaStyle: {
            opacity: 0.8,
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: "#62DAAA",
              },
              {
                offset: 1,
                color: "rgba(255, 255, 255)",
              },
            ]),
          },
          emphasis: {
            focus: "series",
          },
          data: data.value,
        },
      ],
    };
  }
  /**请求数据 */
  async getDataSouce(pream) {
    try {
      let res: any = await getDeviceListData(
        JSON.stringify(pream)
      ).catch((err) => {});
      let json: AjaxData = res;
      if (json.success) {
        switch (pream.energyType) {
          case 1:
            let EleData = this.getEleData(pream.timeType, json.data);
            this.option = this.setOpction(EleData);
            this.forceUpdate();
            break;
          case 2:
            let waterData = this.getWaterData(pream.timeType, json.data);
            this.option = this.setOpction(waterData);
            this.forceUpdate();
            break;
          default:
            break;
        }
      }
    } catch (error) {}
  }
}

export default CalcModal;
